// **********************************************************************
//                            Project Nitro
//                        ---------------------
//
//  File        : Screen.cpp
//  Description : Screen
//  Author      : Guillaume Delhumeau <guillaume.delhumeau@gmail.com>
//  License     : GNU General Public License 3
//
// **********************************************************************

#include "Screen.h"
#include "Preferences.h"
#include "GameEngine.h"

/************************************************************************/
/* Constructor                                                          */
/************************************************************************/
Screen::Screen():
_time_elapsed(0.0f)
{
	_time_last_frame = CL_System::get_time();
}

/************************************************************************/
/* Create or change current window                                      */
/************************************************************************/
void Screen::manage_window(GameEngine & game_engine)
{
	// Save the old main_window (if valid), so graphics are not lost when screen mode is changed.
	// It is destroyed as "previous_window" does out of scope
	CL_DisplayWindow previous_window = _main_window;

	_width = 800;
	_height = 600;

	CL_DisplayWindowDescription desc;
	desc.set_title("Project Nitro");
	desc.set_size(CL_Size(_width,_height), true);
	if(g_preferences.fullscreen)
	{
		desc.set_fullscreen(true);
		desc.set_decorations(false);
	}
	else
	{
		desc.set_allow_resize(true);
	}
	_main_window = CL_DisplayWindow(desc);
	if(g_preferences.fullscreen)
	{
		_main_window.hide_cursor();
	}
	else
	{
		_main_window.show_cursor();
	}

	_quit_event = _main_window.sig_window_close().connect(&game_engine, &GameEngine::stop);

	CL_PixelBuffer icon = CL_PixelBuffer("resources/icon.png");
	_main_window.set_large_icon(icon);

	display();
}

/************************************************************************/
/* Display (flip buffers)                                               */
/************************************************************************/
void Screen::display()
{
	_main_window.flip(0); 
	CL_KeepAlive::process(); 
	unsigned int now = CL_System::get_time();
	unsigned int frame_time = now - _time_last_frame;
	_time_elapsed = (float) frame_time / 1000.0f;
	_time_last_frame = now;
}